package com.captjack.rest.controller;

import com.captjack.rest.configuration.security.TokenAuthenticationManager;
import com.captjack.rest.entity.SysUser;
import com.captjack.rest.repository.SysUserRepository;
import com.captjack.validator.Result;
import com.captjack.validator.annotation.CommonParamValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.Optional;

/**
 * Description description.....
 *
 * @author Jack Sparrow
 * @version 1.0.0
 * @date 2018/6/3 18:15
 * package com.captjack.rest.controller
 */
@RestController
@RequestMapping(value = "/api", method = {RequestMethod.POST})
public class LoginController extends BaseController {

    /**
     * token管理
     */
    private final TokenAuthenticationManager tokenAuthenticationManager;

    /**
     * 用户操作
     */
    private final SysUserRepository sysUserRepository;

    @CommonParamValidator
    @RequestMapping(value = "/login")
    public Object login(@NotNull(message = "id不能为空") Integer id) {
        // 获取用户
        Optional<SysUser> sysUser = sysUserRepository.findById(id);
        if (!sysUser.isPresent()) {
            return Result.USER_NOT_EXSIST;
        }
        // 登录鉴权
        tokenAuthenticationManager.addAuthentication(getResponse(), sysUser.get());
        return Result.SUCCESS;
    }

    @Autowired
    public LoginController(TokenAuthenticationManager tokenAuthenticationManager, SysUserRepository sysUserRepository) {
        this.tokenAuthenticationManager = tokenAuthenticationManager;
        this.sysUserRepository = sysUserRepository;
    }

}
